package com.cpecc.dao.wuzi;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.cpecc.model.system.User;
import com.cpecc.model.wuzi.BuPei;
import com.cpecc.model.wuzi.WuZi;

@Repository
public class BuPeiDao {

	@Resource
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public void save(BuPei buPei){
		Session session=sessionFactory.getCurrentSession();
		session.save(buPei);
		session.flush();
	}
	
	public boolean cover(BuPei buPei){
		String hql="update BuPei t set t.peiChangJE=?,t.wanChengRQ=?,t.huanJie=? where t.id=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setDouble(0, buPei.getPeiChangJE());
		query.setParameter(1, buPei.getWanChengRQ());
		query.setParameter(2, buPei.getHuanJie());
		query.setString(3, buPei.getId());
		return query.executeUpdate()>0;
	}
	
	public BuPei get(String id){
		return (BuPei) sessionFactory.getCurrentSession().get(BuPei.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<BuPei> getBuPeiList(int huanJie){
		String hql="from BuPei t where t.huanJie.id=? order by t.wuZi.chuKuRQ asc";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setInteger(0, huanJie);
		return query.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<BuPei> getMyBuPeiList(User user,int huanJie){
		String hql="from BuPei t where t.huanJie.id=? and t.user.id=? order by t.wuZi.chuKuRQ asc";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setInteger(0, huanJie);
		query.setString(1, user.getId());
		return query.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<BuPei> getBuPeiByWuZi(WuZi wuZi){
		String hql="from BuPei t where t.wuZi=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter(0, wuZi);
		return query.list();
	}
	
	public boolean hasWuZi(String wuZiId){
		String hql="from BuPei t where t.wuZi.id=? and t.huanJie<805";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, wuZiId);
		return query.list().size()>0;
	}
	
	public boolean hasLiuCheng(User user){
		String hql="from BuPei t where t.user=? and t.huanJie<805";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter(0, user);
		return query.list().size()>0;
	}
	
	@SuppressWarnings("unchecked")
	public List<BuPei> activeBuPei(){
		String hql="from BuPei t where t.huanJie<805";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		return query.list();
	}
}
